package com.kavin.network;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkInfo;

public class NetWorkStateReceiver extends BroadcastReceiver {
    private NetworkUtils.OnChangeListener onChangeListener;

    public NetWorkStateReceiver(NetworkUtils.OnChangeListener onChangeListener) {
        this.onChangeListener = onChangeListener;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        if (onChangeListener == null) {
            return;
        }
        //获得ConnectivityManager对象
        ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connMgr == null) {
            onChangeListener.onChange(null, false);
            return;
        }

        //System.out.println("网络状态发生变化");
        //检测API是不是小于21，因为到了API21之后getNetworkInfo(int networkType)方法被弃用
        if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.LOLLIPOP) {

            NetworkInfo[] networkInfos = connMgr.getAllNetworkInfo();
            if (networkInfos != null) {
                for (int i = 0; i < networkInfos.length; ++i) {
                    NetworkInfo networkInfo = networkInfos[i];
                    if (networkInfo.getState() == NetworkInfo.State.CONNECTED) {
                        onChangeListener.onChange(networkInfo, networkInfo.isConnected());
                        return;
                    }
                }
            }

            onChangeListener.onChange(null, false);

        } else {
            //这里的就不写了，前面有写，大同小异
            //System.out.println("API level 大于21");
            //获取所有网络连接的信息
            Network[] networks = connMgr.getAllNetworks();
            if (networks != null) {
                //通过循环将网络信息逐个取出来
                for (int i = 0; i < networks.length; i++) {
                    //获取ConnectivityManager对象对应的NetworkInfo对象
                    NetworkInfo networkInfo = connMgr.getNetworkInfo(networks[i]);
                    if (networkInfo.isConnected()) {
                        onChangeListener.onChange(networkInfo, networkInfo.isConnected());
                        return;
                    }
                }
            }

            onChangeListener.onChange(null, false);

        }


    }
}
